package com.br3akr.rollerClient.client;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Properties;

import com.br3akr.rollerTransferProtocol.transferProtocol.FromServer;

public class ClientThread extends Thread {
	private Socket socket;
	private ObjectOutputStream out;
	private ObjectInputStream in;
	private String hostName;
	private int port;
	private Client client;
    
    public ClientThread(Client client) {
    	super("ClientThread");
		this.client = client;
		Properties prop = new Properties();
		
		try {
			prop.load(this.getClass().getClassLoader()  
                .getResourceAsStream("config/app/config.properties"));
			hostName = prop.getProperty("host");
			String portSt = (String)prop.getProperty("port");
			port = new Integer(portSt).intValue();
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
	
    public void run() {
			try {
				socket = new Socket(hostName, port);
				out = new ObjectOutputStream(socket.getOutputStream());
				client.setOut(out);
				in = new ObjectInputStream(socket.getInputStream());
			} catch (UnknownHostException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			while (true) {
				FromServer fromServer;
				try {
					fromServer = (FromServer)in.readObject();
					client.updatePlayer(fromServer.getUpdateMessage(), fromServer.getPlayerState(), fromServer.getPlayers());
				} catch (IOException e) {
					client.updatePlayer(e.getMessage(), null, null);
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					client.updatePlayer(e.getMessage(), null, null);
					e.printStackTrace();
				}
			}
    }
}